﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using CustomersSuppliersBusinessLayer;
using CustomersSuppliersDataLayer;
using System.Collections;
using WebHelper.Helpers;

namespace CustomersSuppliersWebApplication
{
    public partial class WebFormPersons : WebFormBase
    {
        public Guid? Dealer_ID
        {
            get
            {
                return string.IsNullOrEmpty(this.Request[BLDealer.PropertiesNames.Dealer_ID]) ? (Guid?)null : new Guid(this.Request[BLDealer.PropertiesNames.Dealer_ID]);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                InitializeTelerikRequest(this.RadTextBoxSearch, "onkeyup");
                BLDealer dealer = new BLDealer();
                dealer.Dealer_ID = this.Dealer_ID;
                dealer.LoadByIdentifiers();
                this.PageTitle ="مسئولين الاتصال /"+ dealer.Dealer_NameAr;
            }
        }
        protected void RadTextBoxSearch_TextChanged(object sender, EventArgs e)
        {
            this.getPersons();
            this.RadGridResults.Rebind();
        }
        protected void RadGridResults_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                this.getPersons();
            }
        }
        protected void RadGridResults_ItemCreated(object sender, GridItemEventArgs e)
        {
            //pager
            if (e.Item is GridPagerItem)
            {
                GridPagerItem item = e.Item as GridPagerItem;
                Button changePageSize = (Button)e.Item.FindControl("ChangePageSizeLinkButton");
                changePageSize.Text = "تغيير";
                Button goTO = (Button)e.Item.FindControl("GoToPageLinkButton");
                goTO.Text = "تغيير";
                Label itesNumberLabel = (Label)e.Item.FindControl("ChangePageSizeLabel");
                itesNumberLabel.Text = "          عدد الصفوف :";
                Label goTOLabel = (Label)e.Item.FindControl("GoToPageLabel");
                goTOLabel.Text = "صفحة :";
                Label ofLabel = (Label)e.Item.FindControl("PageOfLabel");
                ofLabel.Text = "من " + item.Paging.PageCount.ToString();
            }
        }
        protected void RadGridResults_ItemCommand(object sender, GridCommandEventArgs e)
        {
            //set default value
            if (e.CommandName == RadGrid.InitInsertCommandName && e.Item.OwnerTableView.Name.ToLower()=="Persons".ToLower())
            {
                e.Canceled = true;
                System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();
                newValues[BLPerson.PropertiesNames.Person_NameAr] = "***";
                e.Item.OwnerTableView.InsertItem(newValues);
            }

        }
        protected void RadGridResults_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            Hashtable newValues = new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            if (e.Item.OwnerTableView.Name.ToLower() == "Persons".ToLower())
            {
                BLPerson Person = new BLPerson();
                if (newValues[BLPerson.PropertiesNames.Person_Code] != null)
                {
                    Person.Person_Code = newValues[BLPerson.PropertiesNames.Person_Code].ToString();
                }
                if (newValues[BLPerson.PropertiesNames.Person_NameAr] != null && newValues[BLPerson.PropertiesNames.Person_NameAr].ToString().Trim() != "")
                {
                    Person.Person_NameAr = newValues[BLPerson.PropertiesNames.Person_NameAr].ToString();
                }
                else
                {
                    this.ShowNotification("من فضلك قم بادخال الاسم", NotificationIconType.Warning);
                    e.Canceled = true;
                    return;
                }
                if (newValues[BLPerson.PropertiesNames.Person_NameEn] != null)
                {
                    Person.Person_NameEn = newValues[BLPerson.PropertiesNames.Person_NameEn].ToString();
                }
                if (newValues[BLPerson.PropertiesNames.Person_Notes] != null)
                {
                    Person.Person_Notes = newValues[BLPerson.PropertiesNames.Person_Notes].ToString();
                }
                Person.Dealer_ID = this.Dealer_ID;
                Person.Person_Search = StringHelper.ToUniqueStatement(Person.Person_Code + Person.Person_NameAr + Person.Person_NameEn + Person.Person_Notes);
                Person.AutoSave();
                if (Person.Error == null)
                {
                    this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                }
                else
                {
                    this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                    e.Canceled = true;
                    return;
                }
            }
            else if (e.Item.OwnerTableView.Name.ToLower() == "Contacts".ToLower())
            {
                BLContact Contact = new BLContact();
                if (newValues[BLContact.PropertiesNames.Contact_Value] != null && newValues[BLContact.PropertiesNames.Contact_Value].ToString().Trim() != "")
                {
                    Contact.Contact_Value = newValues[BLContact.PropertiesNames.Contact_Value].ToString();
                }
                else
                {
                    this.ShowNotification("من فضلك قم بادخال الاتصال", NotificationIconType.Warning);
                    e.Canceled = true;
                    return;
                }
                Contact.Person_ID = new Guid(e.Item.OwnerTableView.ParentItem.GetDataKeyValue(BLPerson.PropertiesNames.Person_ID).ToString());
                RadComboBox radComboBoxContactTypes = (RadComboBox)editedItem.FindControl("RadComboBoxContactTypes");
                if (radComboBoxContactTypes.SelectedValue != "")
                {
                    Contact.ContactType_ID = new Guid(radComboBoxContactTypes.SelectedValue);
                }
                Contact.AutoSave();
                if (Contact.Error == null)
                {
                    this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                }
                else
                {
                    this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                    e.Canceled = true;
                    return;
                }
            }
        }
        protected void RadGridResults_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            Hashtable newValues = new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            if (e.Item.OwnerTableView.Name.ToLower() == "Persons".ToLower())
            {
                BLPerson Person = new BLPerson();
                Person.Person_ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLPerson.PropertiesNames.Person_ID].ToString());
                Person.LoadByIdentifiers();
                if (newValues[BLPerson.PropertiesNames.Person_Code] != null)
                {
                    Person.Person_Code = newValues[BLPerson.PropertiesNames.Person_Code].ToString();
                }
                if (newValues[BLPerson.PropertiesNames.Person_NameAr] != null && newValues[BLPerson.PropertiesNames.Person_NameAr].ToString().Trim() != "")
                {
                    Person.Person_NameAr = newValues[BLPerson.PropertiesNames.Person_NameAr].ToString();
                }
                else
                {
                    this.ShowNotification("من فضلك قم بادخال الاسم", NotificationIconType.Warning);
                    e.Canceled = true;
                    return;
                }
                if (newValues[BLPerson.PropertiesNames.Person_NameEn] != null)
                {
                    Person.Person_NameEn = newValues[BLPerson.PropertiesNames.Person_NameEn].ToString();
                }
                if (newValues[BLPerson.PropertiesNames.Person_Notes] != null)
                {
                    Person.Person_Notes = newValues[BLPerson.PropertiesNames.Person_Notes].ToString();
                }
                Person.Dealer_ID = this.Dealer_ID;
                Person.Person_Search = StringHelper.ToUniqueStatement(Person.Person_Code + Person.Person_NameAr + Person.Person_NameEn + Person.Person_Notes);
                Person.AutoSave();
                if (Person.Error == null)
                {
                    this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                }
                else
                {
                    this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                    e.Canceled = true;
                    return;
                }
            }
            else if (e.Item.OwnerTableView.Name.ToLower() == "Contacts".ToLower())
            {
                BLContact Contact = new BLContact();
                Contact.Contact_ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLContact.PropertiesNames.Contact_ID].ToString());
                Contact.LoadByIdentifiers();
                if (newValues[BLContact.PropertiesNames.Contact_Value] != null && newValues[BLContact.PropertiesNames.Contact_Value].ToString().Trim() != "")
                {
                    Contact.Contact_Value = newValues[BLContact.PropertiesNames.Contact_Value].ToString();
                }
                else
                {
                    this.ShowNotification("من فضلك قم بادخال الاتصال", NotificationIconType.Warning);
                    e.Canceled = true;
                    return;
                }
                Contact.Person_ID = new Guid(e.Item.OwnerTableView.ParentItem.GetDataKeyValue(BLPerson.PropertiesNames.Person_ID).ToString());
                RadComboBox radComboBoxContactTypes = (RadComboBox)editedItem.FindControl("RadComboBoxContactTypes");
                if (radComboBoxContactTypes.SelectedValue != "")
                {
                    Contact.ContactType_ID = new Guid(radComboBoxContactTypes.SelectedValue);
                }
                Contact.AutoSave();
                if (Contact.Error == null)
                {
                    this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                }
                else
                {
                    this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                    e.Canceled = true;
                    return;
                }

            }
        }
        protected void RadGridResults_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            if (e.Item.OwnerTableView.Name.ToLower() == "Persons".ToLower())
            {
                BLPerson Person = new BLPerson();
                Person.Person_ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLPerson.PropertiesNames.Person_ID].ToString());
                Person.DeleteByIdentifiers();
                if (Person.Error == null)
                {
                    this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
                }
                else
                {
                    this.ShowNotification("حدث خطا اثناء الحذف", NotificationIconType.Error);
                    return;
                }
            }
            else if (e.Item.OwnerTableView.Name.ToLower() == "Contacts".ToLower())
            {
                BLContact Contact = new BLContact();
                Contact.Contact_ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLContact.PropertiesNames.Contact_ID].ToString());
                Contact.DeleteByIdentifiers();
                if (Contact.Error == null)
                {
                    this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
                }
                else
                {
                    this.ShowNotification("حدث خطا اثناء الحذف", NotificationIconType.Error);
                    return;
                }
            }
        }
        protected void RadGridResults_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                if( e.Item.OwnerTableView.Name.ToLower() == "Persons".ToLower())
                {
                    //width
                    GridEditableItem editedItem = e.Item as GridEditableItem;
                    GridEditManager editMan = editedItem.EditManager;
                    GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)(editMan.GetColumnEditor(BLPerson.PropertiesNames.Person_Notes));
                    editor.TextBoxMode = TextBoxMode.MultiLine;
                    editor.TextBoxControl.Width = Unit.Pixel(300);
                    editor.TextBoxControl.Height = Unit.Pixel(40);
                }
                else if (e.Item.OwnerTableView.Name.ToLower() == "Contacts".ToLower())
                {
                    //combobox ContactsTypes
                    RadComboBox radComboBoxContactsTypes = (RadComboBox)e.Item.FindControl("RadComboBoxContactTypes");
                    radComboBoxContactsTypes.DataSource = CashVariables.ContactTypeCollection;
                    radComboBoxContactsTypes.DataTextField = BLContactType.PropertiesNames.ContactType_NameAr;
                    radComboBoxContactsTypes.DataValueField = BLContactType.PropertiesNames.ContactType_ID;
                    radComboBoxContactsTypes.DataBind();
                    if (e.Item.ItemIndex != -1)
                    {
                        BLContact contact = (BLContact)e.Item.DataItem;
                        radComboBoxContactsTypes.SelectedValue = contact.ContactType_ID.ToString();
                    }
                }
            }
        }
        protected void RadGridResults_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
        {
            GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem;
            if (e.DetailTableView.Name.ToLower() == "Contacts".ToLower())
            {
                Guid Person_ID = new Guid(dataItem.GetDataKeyValue(BLPerson.PropertiesNames.Person_ID).ToString());
                BLContactCollection ContactCollection = new BLContactCollection();
                ContactCollection.Template.AddFilter(LogicalOperators.And, BLContact.PropertiesNames.Person_ID, FilterOperators.Equal, Person_ID, typeof(Guid));
                ContactCollection.Template.AddSort(BLContact.PropertiesNames.ContactType_ID,true);
                ContactCollection.Load();
                for (int i = 0; i < ContactCollection.Count; i++)
                {
                    int index = CashVariables.ContactTypeCollection.FindByIentifier(ContactCollection[i].ContactType_ID);
                    if (index != -1)
                    {
                        ContactCollection[i].ContactType_NameAr = CashVariables.ContactTypeCollection[index].ContactType_NameAr;
                    }
                }

                e.DetailTableView.DataSource = ContactCollection;
            }
        }


        private void getPersons()
        {
            BLPersonCollection PersonCollection = new BLPersonCollection();
            //sort
            PersonCollection.Template.AddSort(BLPerson.PropertiesNames.Person_RowNumber, false);
            
            //Dealer filter
            PersonCollection.Template.AddFilter(LogicalOperators.And, BLPerson.PropertiesNames.Dealer_ID, FilterOperators.Equal, this.Dealer_ID, typeof(Guid));
            
            //Personsearch filter
            PersonCollection.Template.AddFilter(LogicalOperators.And, BLPerson.PropertiesNames.Person_Search, FilterOperators.Contains, this.RadTextBoxSearch.Text, typeof(string));
            
            //load
            PersonCollection.Load();

            
            if (PersonCollection.Error != null)
            {
                this.ShowNotification("حدث خطا اثناء استعراض البيانات", NotificationIconType.Error);
            }
            this.RadGridResults.DataSource = PersonCollection;
            this.RadGridResults.MasterTableView.DataKeyNames = BLPerson.PropertiesNames.Identifiers;
        }

    }
}